﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JustinAngel.Neurons.Framework;
using JustinAngel.Neurons.Framework.Helpers;
using JustinAngel.Neurons.Pages.Main;
using Microsoft.Devices;

namespace JustinAngel.Neurons.Services
{
    public class ZuneMediaHubIntegrationService : IZuneMediaHubIntegrationService
    {
        [Dependency]
        public IImageService ImageServiceInstance { get; set; }

        static object mutex = new object();
        public void PlayingVideo(VideoItemViewModel video)
        {
            ImageServiceInstance.GetImageData(video.HighResImageUrl.OriginalString, 
                                              video.YoutubeUrl.OriginalString, 
                                             (img, state) =>
            {
                try
                {
                    var s = state as VideoItemViewModel;
                    if (img != null)
                    {
                        Stream HistoryTileImageStream = BuildTile(img, 173, 173);
                        Stream NowPlayingTileImageStream = BuildTile(img, 358, 358);
                        if (HistoryTileImageStream != null)
                        {
                            lock (mutex)
                            {
                                MediaHistoryItem item = new MediaHistoryItem();
                                item.Source = s.YoutubeUrl.OriginalString;
                                item.PlayerContext.Add("history", "True");
                                item.PlayerContext.Add("historyTitle", s.Title);
                                item.PlayerContext.Add("historyYouTubeUrl", s.YoutubeUrl.OriginalString);
                                item.Title = "Neurons - " + video.GroupDisplayName;

                                item.ImageStream = HistoryTileImageStream;
                                MediaHistory.Instance.WriteRecentPlay(item);

                                item.ImageStream = NowPlayingTileImageStream;
                                MediaHistory.Instance.NowPlaying = item;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // just move on if writing history fails, it's not mission critical
                }
            }, video);
        }

        Stream BuildTile(ImageSource image, int width, int height)
        {
            Grid g = new Grid();
            g.Width = width;
            g.Height = height;
            Image img = new Image();
            img.Source = image;
            img.Stretch = Stretch.UniformToFill;
            img.HorizontalAlignment = HorizontalAlignment.Stretch;
            img.VerticalAlignment = VerticalAlignment.Stretch;
            g.Children.Add(img);
            g.UpdateLayout();
            WriteableBitmap b = new WriteableBitmap(g, null);

            // attempt to save until stream size is small enough to fit
            int jpegQuality = 80;
            Stream compositeStream;
            do
            {
                compositeStream = new MemoryStream();
                b.SaveJpeg(compositeStream, width, height, 0, jpegQuality);
                compositeStream.Seek(0, SeekOrigin.Begin);
                jpegQuality -= 10;
            } while (compositeStream.Length > 16383 && jpegQuality > 0);
            return compositeStream;
        }

        public VideoItemViewModel LoadHistoryOrNowPlayingTileClick(NavigationContext NavigationContext)
        {
            if (!NavigationContext.QueryString.ContainsKey("history"))
                return null;

            var historyTitle = NavigationContext.QueryString["historyTitle"];
            var historyYouTubeUrl = new Uri(NavigationContext.QueryString["historyYouTubeUrl"]);
            var result = new VideoItemViewModel(historyYouTubeUrl, historyTitle);
            return result;
        }
    }
}
